import {
  app,
  BrowserWindow,
  Menu
} from 'electron'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development' ?
  `http://localhost:8080` :
  `file://${__dirname}/index.html`

function sendAction(action, ...params) {
  const win = BrowserWindow.getAllWindows()[0];
  if (process.platform === 'darwin') {
    win.restore()
  }
  win.webContents.send(action, ...params);
}

const template = [{
    label: '文件',
    submenu: [{
      label: '退出',
      role: 'close'
    }]
  },
  {
    label: '后退',
    click(item, focusedWindow) {
      if (focusedWindow) {
        console.log('click');
        sendAction('back');
      }
    }
  },
  {
    label: '前进',
    click() {
      sendAction('forward')
    }
  },
  {
    label: '编辑',
    submenu: [{
        label: '撤销',
        role: 'undo'
      },
      {
        label: '重做',
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        label: '剪切',
        role: 'cut'
      },
      {
        label: '复制',
        role: 'copy'
      },
      {
        label: '粘贴',
        role: 'paste'
      },
      {
        label: '格式刷',
        role: 'pasteandmatchstyle'
      },
      {
        label: '删除',
        role: 'delete'
      },
      {
        label: '全选',
        role: 'selectall'
      }
    ]
  },
  {
    label: '视图',
    submenu: [{
        label: '重新加载',
        role: 'reload'
      },
      {
        label: '强制重载',
        role: 'forcereload'
      },
      {
        label: '开发者选项',
        role: 'toggledevtools'
      },
      {
        type: 'separator'
      },
      {
        label: '复原',
        role: 'resetzoom'
      },
      {
        label: '缩小',
        role: 'zoomin'
      },
      {
        label: '放大',
        role: 'zoomout'
      },
      {
        type: 'separator'
      },
      {
        label: '全屏',
        role: 'togglefullscreen'
      }
    ]
  },
  {
    label: '窗口',
    submenu: [{
        label: '最小化',
        role: 'minimize'
      },
      {
        label: '关闭',
        role: 'close'
      }
    ]
  },
  {
    label: '帮助',
    submenu: [{
      label: '更多',
      click() {
        require('electron').shell.openExternal('https://electronjs.org')
      }
    }]
  }
]

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

const {
  ipcMain
} = require('electron')
//const base64 = require('base64-img')
const request = require('request')
const electron = require('electron')
var fs = require('fs')
//var iconv = require('iconv-lite')
//var readline = require('readline');
//var chokidar = require('chokidar')
//var watch = require('watch')
//const imgPath = "C:/ProgramData/TOPCON/LegacyCapture/"
import {
  imgPath
} from '../renderer/js/config';
import {
  infoPath
} from '../renderer/js/config';
import {
  BackURL
} from '../renderer/js/config';
var patientData
var userToken;

// 获取token，上传图像需要
ipcMain.on('sendToken', (event, arg) => {
  console.log('sendToken', arg)
  userToken = arg
})

//图像上传函数
function upload(imgname, url, token) {
  // let imgData = base64.base64Sync(imgname)
  var formData = {
    file: fs.createReadStream(imgname)
  }
  request({
    url: url,
    method: 'POST',
    formData: formData,
    // formData: fs.createReadStream(imgname),
    headers: {
      'Content-type': 'multipart/form-data',
      'token': token
    }
  }, function(err, response, body) {
    // console.log('err',err)
    if (err) {
      return console.error('upload failed:', err);
    }
    console.log('Upload successful!  Server responded with:', body);
    mainWindow.webContents.send('upload', JSON.parse(body))
    // console.log('response:', response)
  })
}

//检测新增图像并上传
function monitorImg(imgPath, url) {
  var imgname
  fs.watch(imgPath, function(eventType, filename) {
    imgname = imgPath + filename
    let regExp = /\.THUMB$/
    if (eventType == "rename" && fs.existsSync(imgname) && regExp.test(imgname)) {
      console.log("upload image is :", imgname);
      fs.readFile(infoPath, 'utf8', function(err, data) {
        if (err) throw err;
        patientData = JSON.parse(data);
        console.log(patientData);
        mainWindow.webContents.send('patientInfo', patientData)
      })
      upload(imgname, url, userToken);
    }
  })
}
monitorImg(imgPath, BackURL + 'upload')


function createWindow() {
  /**
   * Initial window options
   */
  const {
    width,
    height
  } = electron.screen.getPrimaryDisplay().workAreaSize;

  console.log('width', width)
  console.log('height', height)

  mainWindow = new BrowserWindow({
    height: height,
    useContentSize: true,
    width: width
  })

  console.log('winURL', winURL)
  mainWindow.loadURL(winURL)
  win_event(mainWindow)

  mainWindow.on('closed', () => {
    mainWindow = null
  })

}

function win_event(win) {
  win.webContents.on('new-window', function(event, url, fname, disposition, options) {
    console.log('window url', url)
    let childWindow;
    childWindow = new BrowserWindow({
      height: 1080,
      width: 1500
    });
    // childWindow.webContents.openDevTools()
    win_event(childWindow);
    childWindow.loadURL(url);
    event.preventDefault();
  })
}

app.commandLine.appendSwitch("--disable-http-cache")

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */